package com.gxh.interceptor;

import com.gxh.constant.JwtClaimsConstant;
import com.gxh.context.BaseContext;
import com.gxh.properties.JwtProperties;
import com.gxh.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验 + 自动续期的拦截器
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    private static final long RENEW_THRESHOLD = 10 * 60 * 1000; // 10分钟

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        String token = request.getHeader(jwtProperties.getUserTokenName());

        try {
            log.info("jwt校验: {}", token);

            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("当前用户id：{}", userId);
            BaseContext.setCurrentId(userId);

            // ✅ 用 JwtUtil 的方法判断是否需要续期
            if (JwtUtil.shouldRenewToken(claims, RENEW_THRESHOLD)) {
                log.info("Token即将过期，自动续期");
                String newToken = JwtUtil.renewToken(
                        jwtProperties.getUserSecretKey(),
                        jwtProperties.getUserTtl(),
                        claims
                );
                response.setHeader("Renew-Token", newToken);
            }

            return true;

        } catch (io.jsonwebtoken.JwtException e) {
            log.warn("JWT 异常: {}", e.getMessage());
            if (e instanceof io.jsonwebtoken.ExpiredJwtException) {
                // ✅ Token 已过期，但仍可以解析出 claims
                Claims claims = ((io.jsonwebtoken.ExpiredJwtException) e).getClaims();
                Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
                log.info("当前用户id（来自过期Token）：{}", userId);
                BaseContext.setCurrentId(userId);

                // ✅ 续期生成新 Token
                String newToken = JwtUtil.renewToken(
                        jwtProperties.getUserSecretKey(),
                        jwtProperties.getUserTtl(),
                        claims
                );
                // 设置新 Token 到响应头
                response.setHeader("Renew-Token", newToken);
                // ✅ 可选：是否继续执行请求？取决于你的业务需求
                return true; // 放行请求，前端可收到新 Token 并替换旧 Token
            }
            // 其他 JWT 错误（如签名错误、格式错误等）
            response.setStatus(401);
            return false;
        }

    }
}

